//app.js
import utils from './utils/utils.js';

App({
    globalData: {
        openID: 'miand',
        uid: 0,
        userInfo: {},
        txUserInfo: {},
        proxuUser: {},
        loginType: 0,
        agent: {},
        longitude: 120.1551500000,
        latitude: 30.2741500000,
        deviceSn: '',// 扫设备二维码进入 读取的设备SN,
        miniprogram_appid: "", // 微信分小程序APPID
        create_wxfree: 0,
        conduct_sn: "",
        isClick: true,
        wxfree_isClick: true,
        checkNum: 0,
        sessionKey: "",
        app_timer: "", // 定时器
    },
    onLaunch: function (options) {

    },
    onShow: function (options) {
        let create_wxfree = this.globalData.create_wxfree;
        if (options.scene === 1038 && create_wxfree == 1) {
            let miniprogram_appid = this.globalData.miniprogram_appid;
            // 场景值1038：从被打开的小程序返回
            const {appId, extraData} = options.referrerInfo;
            if (appId === miniprogram_appid && extraData) { // miniprogram_appid由【创建订单】返回，检查是否等于appId

                this.globalData.wxfree_isClick = false; // 阻止用户重复点击
                let query_id = extraData.query_id;
                // 用户确认租借成功，重置创建状态
                this.globalData.create_wxfree = 0;

                // 校验用户是否确认租借
                this.queryOrderStatus(query_id);
            } else {
                if (miniprogram_appid) {

                    this.globalData.wxfree_isClick = true; // 允许用户点击

                    // 重置微信分小程序appid
                    this.globalData.miniprogram_appid = "";
                    let sn = this.globalData.conduct_sn;
                    let that = this;
                    // 用户未确认租借充电宝,那么弹出提示框，让用户押金租借
                    wx.showModal({
                        title: '提示',
                        content: '获取免押失败，是否交押金使用？',
                        success: function (sm) {
                            if (sm.confirm) {
                                // 用户点击了确定，那么交押金租借
                                that.startBorrow(sn);
                                that.globalData.conduct_sn = "";
                            } else if (sm.cancel) {
                                wx.showToast({
                                    title: "您点击了取消",
                                    icon: 'none',
                                    duration: 2000
                                });
                            }
                        }
                    })
                }
            }
        }

    },
    // 查询用户是否确认租借
    queryOrderStatus: function (query_id) {
        wx.showLoading({
            title: '请稍后...',
            mask: true
        });
        let that = this;
        utils.httpRequest('/queryWxfreeStatus', {
            query_id: query_id
        }, function (res) {
            wx.hideLoading();
            if (res.code == 1) {
                // 用户微信分订单确认租借
                that.startFreeBorrow(res.data.used_id, res.data.sn);
            } else {
                wx.showToast({
                    title: res.msg,
                    icon: 'none',
                    duration: 2000
                });
            }
        })
    },
    // ==================== 微信免押租借 ==================================
    startFreeBorrow(used_id, sn) {
        let that = this;
        wx.showLoading({
            title: '请稍后...',
            mask: true
        });
        utils.httpRequest('/deviceBorrow', {
            sn: sn,
            freeDeposit: 1,
            used_id: used_id
        }, function (res) {
            switch (res.code) {
                case 1:
                    // 租借设备
                    wx.hideLoading();
                    wx.navigateTo({
                        url: '../onLoan/onLoan?data=' + JSON.stringify(res.data)
                    });
                    break;
                case 4:
                    // 租借命令发送失败
                    wx.hideLoading();
                    wx.showToast({
                        title: res.data.msg,
                        icon: 'none',
                        duration: 2000
                    });
                    break;
                default:
                    wx.hideLoading();
                    break;
            }
        }, function () {
            wx.hideLoading();
        })
    },

    //  ==================== 交押金租借 =======================
    startBorrow(sn) {
        let that = this;
        if (that.globalData.isClick) {
            wx.showLoading({
                title: '请稍后...',
                mask: true
            })
            that.globalData.isClick = false;
            utils.httpRequest('/deviceBorrow', {
                sn: sn,
                freeDeposit: 0
            }, function (res) {
                switch (res.code) {
                    case 1://开始租借
                        that.globalData.isClick = true;
                        wx.hideLoading();
                        wx.navigateTo({
                            url: '../onLoan/onLoan?data=' + JSON.stringify(res.data)
                        });
                        break;
                    case 3://余额不足
                        utils.wxPayPayment(res.data.amount, 1, res.data.sn, 0, function (order_id) {
                            that.globalData.isClick = true;
                            // 查询用户是否支付
                            if (order_id != null) {
                                that.checkOrderStatus(order_id);
                                that.globalData.isClick = true;
                            }
                        }, function () {
                            that.globalData.isClick = true;
                            wx.hideLoading();
                        });
                        break;
                    case 4: // 存在未支付的金额
                        wx.hideLoading();
                        wx.showModal({
                            title: '温馨提示',
                            content: res.msg,
                            confirmText: "马上查看",
                            success(result) {
                                if (result.confirm) {
                                    // 用户点击了确认，跳转到要支付的页面, 押金补足支付
                                    wx.navigateTo({
                                        url: '../payMoney/payMoney?used_id=' + res.data.used_id
                                    });
                                } else {
                                    wx.showToast({
                                        title: "您点击了取消",
                                        icon: 'none',
                                        duration: 2000
                                    });
                                    that.setData({
                                        isClick: true
                                    });
                                }
                            }
                        });
                        break;
                    default:
                        that.globalData.isClick = true;
                        wx.hideLoading();
                        break;
                }
            }, function () {
                that.globalData.isClick = true;
                wx.hideLoading();
            })
        }
    },

    // ================== 校验用户用户是否支付成功（微信分确认不在这里进行判断） ===================
    checkOrderStatus: function (order_id) {
        let that = this;
        let check = that.globalData.checkNum;
        check++;
        that.globalData.checkNum = check;
        if (that.globalData.checkNum < 25) {
            utils.httpRequest('/checkOrderStatus', {
                order_id: order_id,
                freeDeposit: 0
            }, function (res) {
                if (res.data.status == 1) {
                    clearInterval(that.globalData.app_timer);
                    wx.hideLoading();
                    that.startBorrow(res.data.sn);
                } else {
                    var app_timer = setTimeout(() => {
                        that.checkOrderStatus(order_id);
                    }, 3000)
                    that.globalData.app_timer = app_timer;
                }
            }, function () {
                wx.hideLoading();
            })
        } else {
            wx.hideLoading();
            wx.showToast({
                title: "订单异常,请联系客服",
                icon: 'none',
                duration: 2000
            });
        }
    },
    onHide: function () {
        clearInterval(this.globalData.app_timer);
    },

});
